from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from database import get_db
from schemas.worker_schemas import WorkerCreate, WorkerUpdate
from services.auth_service import require_user

from config import *  # 导入所有配置
from models.user_models import *

from services.user_service import get_all_users,get_user,create_user,delete_user,update_user

router = APIRouter()

# 查询获取所有医护人员信息
@router.get("/workers")
def get_workers(db: Session = Depends(get_db),
                user=Depends(require_user(UserType.ADMIN, UserType.WORKER))):
    return get_all_users(UserType.WORKER,db)

# 查询单个医护人员的信息
@router.get("/workers/{worker_id}")
def get_worker(worker_id:int,db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN))):
    return get_user(UserType.WORKER,db,worker_id)

# 创建医护人员账户
@router.post("/workers")
def create_worker(worker: WorkerCreate,
                  db: Session = Depends(get_db),
                  user=Depends(require_user(UserType.ADMIN))):
    return create_user(UserType.WORKER,db,worker)


# 删除医护人员账户
@router.delete("/workers/{worker_id}")
def delete_worker(worker_id: int,
                  db: Session = Depends(get_db),
                  user=Depends(require_user(UserType.ADMIN))):
    return delete_user(UserType.WORKER, db, worker_id)


# 更新工作人员信息
@router.put("/workers/{worker_id}")
def update_worker(worker_id: int,
                  worker_update: WorkerUpdate,
                  db: Session = Depends(get_db),
                  user=Depends(require_user(UserType.ADMIN,UserType.WORKER))):
    if user["user_type"] == 'WORKER' and user['user_ref_id'] != worker_id:
        raise HTTPException(
            status_code=403,
            detail="Permission denied: worker can only update their own information."
        )
    return update_user(UserType.WORKER, db, worker_update, worker_id)